package com.zwy.stack.impl;

import com.zwy.stack.Queue;
/*
    顺序队列
 */
public class QueueArray implements Queue {
    private static final int CAP=10;  //队列默认大小
    private Object[] elements;      //数据的元素数组
    private int capacity; //数组的大小
    private int front;      //队首指针，指向队首
    private int rear;       //队尾指针，指向队尾最后一个位置

    //初始化队列
    public QueueArray(int cap) {
        this.capacity = cap+1;
        elements=new Object[capacity];
        front=rear=0;
    }

    @Override
    public int getSize() {
        return (rear-front+capacity)%capacity;
    }

    @Override
    public boolean isEmpty() {
        return front==rear;
    }

    @Override
    public void enqueue(Object e) {
        if(getSize()==capacity-1)expandSpace();
        elements[rear]=e;
        rear=(rear+1)%capacity;
    }

    /**
     * 拓展空间
     */
    public void expandSpace(){
        Object[]a=new Object[elements.length*2];
        int i=front;int j=0;
        while(i!=rear){
            a[j++]=elements[i];
            i=(i+1)%capacity;
        }
        elements=a;
        capacity=elements.length;
        front=0;rear=j;
    }

    @Override
    public Object dequeue() {
        if(isEmpty()){
            throw  new RuntimeException("");
        }
        Object obj=elements[front];
        elements[front]=null;
        front=(front+1)%capacity;
        return obj;
    }

    @Override
    public Object peek() {
        if(isEmpty()){
            throw  new RuntimeException("");
        }
        return elements[front];
    }
}
